import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //初始值
    pageNow: 1,
    //最多有几页
    pageNum: 0,
      tag:'all',
    bingImageUrl: 'https://cn.bing.com',
      AdminName: new Map
  },
  mutations: {
    //操作state 只能同步
    InitHome(state, pagenum) {
      state.pageNow = 1
      state.pageNum = pagenum
    },

    UpdatePageNow(state, num) {
      state.pageNow = num
    },
    InitBingImageUrl(state, subUrl) {
      state.bingImageUrl += subUrl
    },
      SetTag(state,tag)
      {
          state.tag = tag
      },
      InitAdminName(state,map)
      {
          state.AdminName = map
      }
  },

  actions: {
    //可以异步但是只能commit
    InitHomeAsync(context) {
      let pageNum
      //pageNum从后台获取
      axios.defaults.withCredentials = true;
      axios.defaults.headers.post["Content-Type"] =
          "application/json;charset=utf-8";
      let postData = {
          "tag": this.state.tag
      }
      axios.post("http://shilezhi.club:8082/Api/Blog/GetPageNum",JSON.stringify(postData)).then(
          response=>{
            console.log(response)
            if (response.data.code === 'ok')
            {
              pageNum =  response.data.blog
                console.log('pageNum'+pageNum)
                context.commit('InitHome', pageNum)
            }
            else
            {
              console.log(response.data)
            }
      },
          err=>{
            console.log(err)
          }
      )
    },
    InitBingImageUrlAsync(context) {

      axios.get('').then(
          response => {
            let imageUrl = response.data.images[0].url
            console.log(imageUrl)
            context.commit('InitBingImageUrl', imageUrl)
          },
          err => {
            console.log('图片加载失败')
          }
      )
    },
      InitAdminNameAsync(context)
      {
          axios.defaults.withCredentials = true
          axios.defaults.headers.post["Content-Type"] =
              "application/json;charset=utf-8"
          let adminMap = new Map()
          axios.get("http://shilezhi.club:8082/Api/User/GetAdminNameMap").then(
              response=>{
                  for (let k of Object.keys(response.data))
                  {
                      adminMap.set(k,response.data[k])
                  }
              },
              err=>{

              }
          )
          context.commit('InitAdminName',adminMap)
      }

  },
  modules: {}
})
